package cn.aitrox.ry.util;

import com.google.common.collect.Lists;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import org.apache.commons.io.input.BOMInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class CsvUtil {
    private static final Logger log = LoggerFactory.getLogger(CsvUtil.class);

    public static final String CSV_SUFFIX = "csv";

    public static File writeCSV(String filePath, List<List<String>> data) {
        CSVWriter writer = null;
        try {
            File csvFile = new File(filePath);
            File parentFile = csvFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(csvFile), StandardCharsets.UTF_8);
            outputStreamWriter.write(new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF})); // 解决导出的中文乱码，手动加BOM标识
            writer = new CSVWriter(outputStreamWriter);
            List<String[]> writeList = Lists.newArrayList();
            for (List<String> sl : data) {
                writeList.add(sl.toArray(new String[sl.size()]));
            }
            writer.writeAll(writeList);
            return csvFile;
        } catch (IOException e) {
            log.error(LogUtil.genException(e, "CsvUtil.writeCSV", "filePath", filePath));
            return null;
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                log.error(LogUtil.genException(e, "CsvUtil.writeCSV close io fail", "filePath", filePath));
            }
        }
    }

    public static List<List<String>> readCSV(File file) {
        List<List<String>> data = null;
        CSVReader reader = null;
        try {
            Reader fReader = new InputStreamReader(new BOMInputStream(new FileInputStream(file.getPath())), StandardCharsets.UTF_8);
            reader = new CSVReader(fReader);
            List<String[]> readAll = reader.readAll();
            if (null != readAll && readAll.size() > 0) {
                data = readAll.stream().map(x -> {
                    List<String> rowData = new ArrayList<>(x.length);
                    for (int i = 0; i < x.length; i++) {
                        rowData.add(x[i]);
                    }
                    return rowData;
                }).collect(Collectors.toList());
            }
        } catch (Exception e) {
            log.error(LogUtil.genException(e, "CsvUtil.readCSV failed", "fileName", file.getName()));
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error(LogUtil.genException(e, "CsvUtil.readCSV close CSVReader failed", "fileName", file.getName()));
                }
            }
        }
        return data;
    }
}
